#include "StdAfx.h"
#include "FileIO.h"

#include <iostream>
#include <sstream>
#include <fstream>

bool FileIO::LoadFile(vector<FileLine*> &data, const char* fileName)
{
	//open file
	ifstream dataStream (fileName);
	if (!dataStream.is_open())
		return false;

	string lineInFile;
	string lineToParse;
	//until end of file
	while (!dataStream.eof())
    {
		getline (dataStream,lineInFile);
		//while line end not found, read lines and append to string
		lineToParse += lineInFile;
		int index = lineToParse.find_last_of(mLineEnd);
		if (index < 0 || (int) lineToParse.length() <= index)
		{			
			lineToParse += "\n";
			continue;
		}
		
		//removing the line end character
		lineToParse = lineToParse.substr(0,lineToParse.length()-1);

		//cut string down into tokens and save to a new fileline
		FileLine* fLine = new FileLine();
		string token;
		istringstream iss(lineToParse);

		while (getline(iss,token,mTokenEnd))
		{
			fLine->tokens.push_back(token);
		}
		lineToParse = "";

		//add fileline to data vector
		data.push_back(fLine);		
    }
		
	//close file
	dataStream.close();
	return true;
}

bool FileIO::SaveFile(const vector<FileLine*> data, const char* fileName)
{
	//open file
	ofstream dataStream (fileName);
	if (!dataStream.is_open())
		return false;

	//save lines to file
	for (unsigned int i = 0; i < data.size(); ++i)
	{
		//add token end to every token in line
		for (unsigned int j = 0; j < data[i]->tokens.size(); ++j)		
		{
			dataStream << data[i]->tokens[j] << mTokenEnd;
		}
		//add line end to every line
		dataStream << mLineEnd << endl;
	}

	//close file
	dataStream.close();
	return true;
}


